package com.lifesaftypower.product;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public final class ProductRepo {
	public static ArrayList<ProductCategory> Load(Document doc) {
		NodeList categories = doc.getElementsByTagName(ProductCategory.TAG);
		ArrayList<ProductCategory> result = new ArrayList<ProductCategory>();
		for (int i = 0; i < categories.getLength(); i++) {
			Node categoryNode = categories.item(i);
			ProductCategory category = new ProductCategory(categoryNode);
			result.add(category);
		}

		return result;
	}

	public static ArrayList<ProductCategory> Load(String xmlText)
			throws ParserConfigurationException, SAXException, IOException {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder;
			dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(xmlText);
			ArrayList<ProductCategory> result = Load(doc);

			return result;
		} catch (Exception ex) {
			return null;
		}
	}

	public static ArrayList<ProductCategory> Load(InputStream ins)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(ins);
		return Load(doc);

	}

}
